package com.xsm.activitygroup;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.umeng.analytics.MobclickAgent;
import com.xsm.activitygroup.R;
import com.xsm.adapter.BooksAdapter;
import com.xsm.internet.PostMessage;
import com.xsm.object.BookObject;

import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class SearchView extends Activity{
	com.xsm.view.ClearEditText  searchText;
	Button searchButton;
	RelativeLayout loadlayout;
	mYhandler handYhandler;
	ArrayList<BookObject> books=new ArrayList<BookObject>();
	PullToRefreshListView list;
	Context context;
	BooksAdapter badapter;
	SharedPreferences sharedPreferences;
	String bookString;//书名提示
	 ArrayList<String> booknameList;
	 MyAdapter<String> booknameAdapter;
	 int page=0;
	 
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	requestWindowFeature(Window.FEATURE_NO_TITLE);
	setContentView(R.layout.searchview);
	context=this;
	initView();
}

private void  initView(){
	sharedPreferences=getSharedPreferences("XSM", 0);
	  bookString=sharedPreferences.getString("bookname", "");
	  booknameList=new ArrayList<String>();
	handYhandler=new mYhandler();
	list=(PullToRefreshListView)findViewById(R.id.searchlist);
    badapter=new BooksAdapter(this, books);
    list.setAdapter(badapter);
    list.setOnItemClickListener(new OnItemClickListener() {
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			  Intent intent=new Intent();
			  intent.putExtra("ms",books.get(arg2-1));
			  intent.putExtra("index",arg2);
			  intent.putExtra("type", "sell");
			  intent.setClass(context, BookMessage.class);
			 startActivityForResult(intent,2);			
		}
    });
    
    list.setOnRefreshListener(new OnRefreshListener<ListView>() {
		public void onRefresh(PullToRefreshBase<ListView> refreshView) {
			String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
			DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			new Thread(new LoadSearch()).start();
		}
	});
  
    
    
	loadlayout=(RelativeLayout)findViewById(R.id.loadlayout);
	searchText=(com.xsm.view.ClearEditText )findViewById(R.id.searchText);
	
    String bb[]=bookString.split(",");	
    for(int i=0;i<bb.length;i++){
    	booknameList.add(bb[i]);
    }
    
    booknameAdapter=new MyAdapter<String>(context, android.R.layout.simple_dropdown_item_1line,booknameList);
    searchText.setAdapter(booknameAdapter);
   
	
	String[] COUNTRIES = new String[] {};
	searchButton=(Button)findViewById(R.id.searchButton);
	searchButton.setOnClickListener(new OnClickListener() {
		public void onClick(View arg0) {
	loadlayout.setVisibility(View.VISIBLE);		
	new Thread(new LoadSearch()).start();
		}
	});
}

float downY=0,moveY=0,touch=0;
public OnTouchListener touchListener=new OnTouchListener() {
	public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
	downY=event.getY();
	break;
case MotionEvent.ACTION_MOVE:
	moveY=event.getY();
	break;
case MotionEvent.ACTION_UP:
	touch=moveY-downY;
	break;	
default:
	break;
}
		
		return false;
	}
};
class LoadSearch implements Runnable{
	public void run() {
		if(touch>0)
		books.clear();
		page=books.size();
		List params=new ArrayList();
		params.add(new BasicNameValuePair("ASK","searchGoods"));
		params.add(new BasicNameValuePair("bname",searchText.getText().toString().trim()));
		params.add(new BasicNameValuePair("page",page+""));
		PostMessage postMessage=new PostMessage(params);
		String result=postMessage.getResult();
		
		JSONArray array = null;
		try {
			 array=new JSONArray(result);
			JSONObject jobject=new JSONObject();
			for(int i=0;i<array.length();i++){
				jobject=array.optJSONObject(i);
				String bookname=jobject.getString("bookname");
				String releaseType=jobject.getString("buytype");
				String time=jobject.getString("time");
				String price=jobject.getString("price");
				String bookType=jobject.getString("booktype");
				String oner=jobject.getString("username");
				String phone=jobject.getString("phone");
				String message=jobject.getString("explain");
				String school=jobject.getString("school");
				String press=jobject.getString("press");
				String goodsid=jobject.getString("goodsid");
				String author=jobject.getString("author");
				String uid=jobject.getString("userid");
				String gparentid=jobject.getString("gparentid");
				String realprice=jobject.getString("realprice");
				String path=jobject.getString("path");
				BookObject object=new BookObject();
				object.setBookName(bookname);
				object.setReleaseType(releaseType);
				object.setTime(time.substring(0,10));
				object.setPrice(price);
				object.setBookType(bookType);
				object.setOner(oner);
				object.setPhone(phone);
				object.setMessage(message);
				object.setPlace(school);
				object.setPress(press);
				object.setGoodsid(goodsid);
				object.setUserid(uid);
				object.setGparentid(gparentid);
				object.setAuthor(author);
				object.setRealprice(realprice);
				object.setPath(path);
				books.add(object);	
			}
		} catch (Exception e) {
			Log.d("my", e+"");
		}
	Message msg=handYhandler.obtainMessage();
	if(result.equals("-1"))
		msg.what=-1;
	else
	    msg.what=1;
	handYhandler.sendMessage(msg);	
	}
}

class mYhandler extends Handler{
	public void handleMessage(Message msg) {
		if(msg.what==1){
		if(books.size()<8)
			list.setMode(Mode.PULL_DOWN_TO_REFRESH);
		else
			list.setMode(Mode.BOTH);
		loadlayout.setVisibility(View.GONE);	
		badapter.notifyDataSetChanged();
		}else {
			Toast.makeText(context,R.string.neterror,Toast.LENGTH_LONG).show();
		}
		list.onRefreshComplete();
		super.handleMessage(msg);
	}
}

public void Back(View view){
	finish();
}
@Override
protected void onResume() {
	MobclickAgent.onResume(this);
	super.onResume();
}
@Override
protected void onPause() {
	MobclickAgent.onResume(this);
	super.onPause();
}


}
